#include "HumanPlayer.h"
#include "SDL/SDL.h"

HumanPlayer::HumanPlayer(int offsetX,int offsetY,int caseSize){
	this->offsetX = offsetX;
	this->offsetY = offsetY;
	this->caseSize = caseSize;
}

GameInput HumanPlayer::play(const GameEngine& ge){
	GameInput gi;
	SDL_Event event;
	event.type = SDL_MOUSEBUTTONDOWN;// To avoid SDL_QUIT at first loop.
	bool loopAgain = true;
	while(loopAgain){
		SDL_WaitEvent(&event);
		loopAgain = false;
		if (event.type == SDL_MOUSEBUTTONDOWN) {
			position_t p;
			p = get_position_from_pixels(event.button.x, event.button.y);
			if(!ge.getBoard().onBoard(p)&&!ge.getBoard().onGoalZone(p)){
				loopAgain = true;
				continue;
			}
			if (event.button.button == SDL_BUTTON_LEFT) {
				gi.action = GameInput::MOVEBALL;
				gi.place = p;
			}else if (event.button.button == SDL_BUTTON_RIGHT) {
				gi.action = GameInput::PLACEPAWN;
				gi.place = p;
			}
		}else if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) {
			gi.action = GameInput::ENDMOVE;
		}else if(event.type == SDL_QUIT){
			gi.action = GameInput::REQUEST_EXIT;
		}else{
			loopAgain = true;
		}
	}
	return gi;
}

position_t HumanPlayer::get_position_from_pixels(int x, int y){
	x -= offsetX;
	y -= offsetY;
	int i = (x-caseSize)/caseSize;
	if (x < caseSize) i = -1;
	return position_t(i,(Board::h-y/caseSize)-1);
}